import { useEffect, useState } from "react";
import { DateTab } from "./type";
import Style from "./date.module.scss";
import { InsertRowBelowOutlined } from "@ant-design/icons";
import { ParamType, getSearchParam } from "../../reducer/param";
import { ReqGetRecent5DayData } from "../../request/request";
import classNames from "classnames";
import store from "../../reducer";
import { getListScroll } from "../../reducer/listScroll";
import { observer } from "mobx-react-lite";

const A_DAY = 24 * 60 * 60 * 1000;
const TopDate = observer(() => {
  const [activeTab, setActiveTab] = useState<string>("");
  const [tabs, setTabs] = useState<DateTab[]>([]);
  const [offset, setOffset] = useState(0);
  const [moveStart, setMoveStart] = useState(true);

  const searchParam = getSearchParam(store);
  const scrollState = getListScroll(store);

  const handleTabClick = (date: string) => {
    setMoveStart(true);
    const diffDay =
      (new Date(activeTab).valueOf() - new Date(date).valueOf()) / A_DAY;
    // 移动
    setOffset((offset) => offset - diffDay);
    // 改变目标天数
    setActiveTab(date);
  };
  const handleTransitionend = () => {
    console.log("handleTransitionend");
    setMoveStart(false);
    store.searchParam.setSearchDate(activeTab);
  };
  const fetchData = async (param: ParamType) => {
    console.log("fetch");

    const { data } = await ReqGetRecent5DayData(param);
    const targetData = JSON.parse(data.data) as Array<DateTab>;
    const ofs = targetData.findIndex((val) => val.start);
    setOffset(ofs);
    setTabs(targetData);
    setActiveTab(param.date);
  };
  useEffect(() => {
    console.log("date useEffect");

    fetchData(searchParam);
  }, [searchParam]);

  return (
    <div
      className={classNames(Style.container, {
        [Style.moving]: scrollState,
      })}
    >
      <div className={Style.more}>
        <InsertRowBelowOutlined style={{ fontSize: "16px" }} />
        <div>更多日期</div>
      </div>
      <div className={Style.box}>
        <div
          className={classNames(Style.date, {
            [Style.move]: moveStart,
          })}
          style={{
            transform: `translateX(-${10 * offset}%)`,
          }}
          onTransitionEnd={() => handleTransitionend()}
        >
          {tabs.map((tab) => (
            <div
              className={classNames(Style.tab, {
                [Style.active]: tab.date === activeTab,
              })}
              onClick={() => handleTabClick(tab.date)}
              key={tab.date}
            >
              <div className="date">
                {tab.date.slice(tab.date.indexOf("-") + 1)}
              </div>
              <div className="week">{tab.week}</div>
              <div className="price">￥{tab.price}</div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
});
export default TopDate;
